package com.feige.controller;


import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.feige.pojo.Dept;
import com.feige.pojo.User;
import com.feige.pojo.dto.UserDto;
import com.feige.pojo.dto.UserQueryDto;
import com.feige.pojo.vo.UserVo;
import com.feige.result.AjaxResult;
import com.feige.service.DeptService;
import com.feige.service.RoleService;
import com.feige.service.UserService;
import com.feige.utils.CustomCellWriteHandler;
import com.feige.utils.UserDataListener;
import com.feige.utils.common.Admin;
import com.feige.utils.common.BeanUtils;
import com.feige.utils.common.MD5;
import com.feige.utils.jwt.JwtInfo;
import com.feige.utils.jwt.JwtUtils;
import com.feige.utils.string.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author feige
 * @since 2020-07-20
 */
@Api(tags = "用户类")
@RestController
@RequestMapping("/admin/user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private RoleService roleService;

    @Resource
    private DeptService deptService;



    @Value("${download.path}")
    private String path;


    @PreAuthorize("@ss.hasPerm('user:user:list')")
    @ApiOperation(value = "获取管理用户分页列表")
    @PostMapping("/list")
    public AjaxResult index(@RequestBody UserQueryDto userQueryDto) {
        IPage<User> pageParam = userService.listByUserQueryDto(userQueryDto);
        List<UserVo> userVoList = BeanUtils.convertList2List(pageParam.getRecords(), UserVo.class);
        AjaxResult success = AjaxResult.success(userVoList);
        success.put("total",pageParam.getTotal());
        return success;
    }

    @PreAuthorize("@ss.hasPerm('user:user:add')")
    @ApiOperation(value = "新增管理用户和权限")
    @PostMapping("/save")
    public AjaxResult save(@Validated @RequestBody UserDto userDto) {
        boolean save = userService.saveUser(userDto);
        if (save){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @PreAuthorize("@ss.hasPerm('user:user:list')")
    @ApiOperation(value = "获取用户")
    @GetMapping("/get/{id}")
    public AjaxResult get(@PathVariable Long id) {
        User user = userService.getById(id);
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        return AjaxResult.success(userVo);
    }

    @PreAuthorize("@ss.hasPerm('user:user:edit')")
    @ApiOperation(value = "修改用户和权限")
    @PutMapping("/update")
    public AjaxResult updateById(@Validated @RequestBody UserDto userDto) {

        boolean update = userService.updateUser(userDto);
        if (update){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @PreAuthorize("@ss.hasPerm('user:user:edit')")
    @ApiOperation(value = "修改用户的状态或重置密码")
    @PutMapping("/update-pwd-status")
    public AjaxResult update(@RequestBody User user) {

        boolean update = userService.updateById(user);
        if (update){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @PreAuthorize("@ss.hasPerm('user:user:delete')")
    @ApiOperation(value = "删除管理用户")
    @DeleteMapping("/remove/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        boolean remove = userService.removeById(id);
        if (remove){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @PreAuthorize("@ss.hasPerm('user:user:delete')")
    @ApiOperation(value = "根据id列表删除管理用户")
    @DeleteMapping("/batchRemove")
    public AjaxResult batchRemove(@RequestBody List<Long> idList) {
        boolean remove = userService.removeByIds(idList);
        if (remove){
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @PreAuthorize("@ss.hasPerm('user:user:export')")
    @ApiOperation(value = "导出")
    @PostMapping("/export")
    public AjaxResult export(@RequestBody UserQueryDto userQueryDto) {
        IPage<User> pageParam = userService.listByUserQueryDto(userQueryDto);
        List<User> list = pageParam.getRecords();
        String fileName = UUID.randomUUID().toString().replace("-", "").substring(0,8);
        String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        fileName = date + "_" + fileName;
        File file = new File(path + File.separatorChar + fileName + ".xlsx");
        EasyExcel.write(file, User.class).registerWriteHandler(new CustomCellWriteHandler()).sheet("用户表").doWrite(list);
        return AjaxResult.success(fileName + ".xlsx");
    }

    @PreAuthorize("@ss.hasPerm('user:user:import')")
    @ApiOperation(value = "导入")
    @PostMapping("/import")
    public AjaxResult importUser(MultipartFile file,Boolean updateSupport) throws IOException {
        EasyExcel.read(file.getInputStream(),User.class,new UserDataListener(userService,updateSupport)).sheet().doRead();
        return AjaxResult.success(200,"导入成功");
    }

    @ApiOperation(value = "获取用户")
    @GetMapping("/get/profile")
    public AjaxResult getUserProfile(HttpServletRequest request) {
        JwtInfo jwtInfo = JwtUtils.getJwtInfoByJwtToken(request);
        if (StringUtils.isNotNull(jwtInfo)){
            Long id = jwtInfo.getId();
            User user = userService.getById(id);
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
            Set<String> roleName = roleService.selectRoleNameByUserId(id);
            Dept dept = deptService.getById(user.getDeptId());
            AjaxResult success = AjaxResult.success();
            success.put("user",userVo);
            success.put("roleName",roleName);
            success.put("deptName",dept.getDeptName());
            return success;
        }else {
            return AjaxResult.error(500,"后台未获取到登录信息或token解析异常！");
        }
    }


    @PreAuthorize("@ss.hasPerm('user:user:edit')")
    @ApiOperation(value = "修改用户的密码")
    @PutMapping("/update-pwd")
    public AjaxResult updatePwd(HttpServletRequest request,String newPassword,String oldPassword) {
        if (StringUtils.isEmpty(newPassword) || StringUtils.isEmpty(oldPassword)){
            return AjaxResult.error(500,"新密码和旧密码不能为空！");
        }
        if (newPassword.length() < 6 || newPassword.length() > 18){
            return AjaxResult.error(500,"密码长度必须在6~18位");
        }
        if (oldPassword.length() < 6 || oldPassword.length() > 18){
            return AjaxResult.error(500,"密码长度必须在6~18位！");
        }
        if (newPassword.equals(oldPassword)) {
            return AjaxResult.error(500,"新密码不能与旧密码相同！");
        }
        JwtInfo jwtInfo = JwtUtils.getJwtInfoByJwtToken(request);
        if (StringUtils.isNotNull(jwtInfo)){
            Long id = jwtInfo.getId();
            User user = userService.getById(id);
            if (user.getPassword().equals(MD5.encrypt(oldPassword))){
                User user1 = new User();
                user1.setId(id);
                user1.setPassword(MD5.encrypt(newPassword));
                boolean update = userService.updateById(user1);
                if (update){
                    return AjaxResult.success();
                }else {
                    return AjaxResult.error();
                }
            }else {
                return AjaxResult.error(500,"您输入的旧密码和数据库中的不匹配，请重新输入！");
            }
        }else {
            return AjaxResult.error(500,"后台未获取到登录信息或token解析异常！");
        }
    }

}

